import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'

Vue.use(Router)

import Layout from '@/layout'

// 基础路由
export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true
  },
  {
    path: '/register',
    component: () => import('@/views/register/index'),
    hidden: true
  },
  {
    path: '/404',
    component: () => import('@/views/404'),
    hidden: true
  },
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: 'home',
        name: 'Home',
        component: () => import('@/views/home/index'),
        meta: { title: '首页', icon: 'el-icon-s-home' }
      }
    ]
  }
]

// 需要权限的动态路由
export const asyncRoutes = [
  // 客户路由
  {
    path: '/customer',
    component: Layout,
    redirect: '/customer/products',
    meta: { title: '客户服务', icon: 'el-icon-user', roles: ['customer'] },
    children: [
      {
        path: 'products',
        name: 'CustomerProducts',
        component: () => import('@/views/customer/products'),
        meta: { title: '商品列表', icon: 'el-icon-shopping-bag-1' }
      },
      {
        path: 'cart',
        name: 'Cart',
        component: () => import('@/views/customer/cart'),
        meta: { title: '购物车', icon: 'el-icon-shopping-cart-full' }
      },
      {
        path: 'orders',
        name: 'CustomerOrders',
        component: () => import('@/views/customer/orders'),
        meta: { title: '我的订单', icon: 'el-icon-s-order' }
      }
    ]
  },
  // 送水员路由
  {
    path: '/delivery/orders',
    component: Layout,
    children: [
      {
        path: '',
        name: 'DeliveryOrders',
        component: () => import('@/views/delivery/orders'),
        meta: { title: '订单管理', icon: 'el-icon-s-order', roles: ['delivery'] }
      }
    ]
  },
  // 管理员路由 - 数据统计
  {
    path: '/admin/dashboard',
    component: Layout,
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: () => import('@/views/admin/dashboard'),
        meta: { title: '数据统计', icon: 'el-icon-s-data', roles: ['admin'] }
      }
    ]
  },
  // 管理员路由 - 用户管理
  {
    path: '/admin/users',
    component: Layout,
    children: [
      {
        path: '',
        name: 'Users',
        component: () => import('@/views/admin/users'),
        meta: { title: '用户管理', icon: 'el-icon-user', roles: ['admin'] }
      }
    ]
  },
  // 管理员路由 - 送水员管理
  {
    path: '/admin/delivery-staff',
    component: Layout,
    children: [
      {
        path: '',
        name: 'DeliveryStaff',
        component: () => import('@/views/admin/delivery-staff'),
        meta: { title: '送水员管理', icon: 'el-icon-s-custom', roles: ['admin'] }
      }
    ]
  },
  // 管理员路由 - 品牌管理
  {
    path: '/admin/brands',
    component: Layout,
    children: [
      {
        path: '',
        name: 'Brands',
        component: () => import('@/views/admin/brands'),
        meta: { title: '品牌管理', icon: 'el-icon-s-shop', roles: ['admin'] }
      }
    ]
  },
  // 管理员路由 - 商品管理
  {
    path: '/admin/products',
    component: Layout,
    children: [
      {
        path: '',
        name: 'Products',
        component: () => import('@/views/admin/products'),
        meta: { title: '商品管理', icon: 'el-icon-goods', roles: ['admin'] }
      }
    ]
  },
  // 管理员路由 - 订单管理
  {
    path: '/admin/orders',
    component: Layout,
    children: [
      {
        path: '',
        name: 'Orders',
        component: () => import('@/views/admin/orders'),
        meta: { title: '订单管理', icon: 'el-icon-s-order', roles: ['admin'] }
      }
    ]
  }
]

const createRouter = () => new Router({
  mode: 'history',
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
})

const router = createRouter()

// 重置路由
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher
}

// 路由守卫：登录后动态添加路由
let isRouteAdded = false
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  // 增加 userRole 映射，兼容 USER/ADMIN/DELIVERY
  const userRoleRaw = (localStorage.getItem('userRole') || '').toLowerCase()
  const roleMap = {
    'user': 'customer',
    'admin': 'admin',
    'delivery': 'delivery'
  }
  const userRole = roleMap[userRoleRaw] || userRoleRaw
  const whiteList = ['/login', '/register']

  if (token) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      if (!isRouteAdded) {
        // 根据角色动态添加路由，meta.roles 也统一转小写
        const accessRoutes = asyncRoutes.filter(route => {
          if (!route.meta || !route.meta.roles) return true
          return route.meta.roles.map(r => (r || '').toLowerCase()).includes(userRole)
        })
        accessRoutes.forEach(route => {
          router.addRoute(route)
        })
        isRouteAdded = true
        next({ ...to, replace: true })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
    }
  }
})

export default router
